<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>客户管理</el-breadcrumb-item>
      <el-breadcrumb-item>客户信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="input"
            @input="init()"
            clearable
            placeholder="请输入客户名称"
          >
          </el-input>
        </el-col>
        <el-col :span="4" style="float: right">
          <el-button @click="dialogVisible = true" type="primary"
            >添加用户</el-button
          >
          <!-- 添加客户模态框 -->
          <el-dialog title="添加客户" :visible.sync="dialogVisible" width="60%">
            <el-form
              label-width="80px"
              :model="addform"
              :rules="addroles"
              ref="addformref"
            >
              <el-form-item prop="clientname" label="客户名称">
                <el-input v-model="addform.clientname"></el-input>
              </el-form-item>
              <el-form-item prop="sex" label="性别">
                <el-select v-model="addform.sex" placeholder="请选择性别">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="birth" label="生日">
                <el-date-picker
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  v-model="addform.birth"
                  style="width: 100%"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="mobile" label="电话">
                <el-input v-model="addform.mobile"></el-input>
              </el-form-item>
              <el-form-item prop="members" label="是否会员">
                <el-select v-model="addform.members" placeholder="请选择">
                  <el-option label="是" value="是"></el-option>
                  <el-option label="否" value="否"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item style="margin-left: 630px">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="adduser('addformref')"
                  >确 定</el-button
                >
              </el-form-item>
            </el-form>
          </el-dialog>
          <!-- 修改客户信息模态框 -->
          <el-dialog
            title="编辑信息"
            width="60%"
            :visible.sync="editdialogVisible"
            center
          >
            <el-form
              label-width="80px"
              :model="edituserinfo"
              :rules="addroles"
              ref="edituserinforef"
            >
              <el-form-item prop="clientname" label="客户名称">
                <el-input v-model="edituserinfo.clientname"></el-input>
              </el-form-item>
              <el-form-item prop="sex" label="性别">
                <el-select v-model="edituserinfo.sex" placeholder="请选择性别">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="birth" label="生日">
                <el-date-picker
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  v-model="edituserinfo.birth"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="mobile" label="电话">
                <el-input v-model="edituserinfo.mobile"></el-input>
              </el-form-item>
              <el-form-item prop="members" label="是否会员">
                <el-select v-model="edituserinfo.members" placeholder="请选择">
                  <el-option label="是" value="是"></el-option>
                  <el-option label="否" value="否"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item style="margin-left: 630px">
                <el-button @click="editdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="edituser()">确 定</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table border :data="tables" stripe style="margin-top: 5px">
        <!-- 索引列 -->
        <el-table-column type="index" label="客户编号" width="100px">
        </el-table-column>
        <!-- 姓名列 -->
        <el-table-column prop="clientname" label="客户名称"> </el-table-column>
        <!-- 邮箱列 -->
        <el-table-column prop="sex" label="性别"> </el-table-column>
        <!-- 生日 -->
        <el-table-column prop="birth" label="生日"> </el-table-column>
        <!-- 电话 -->
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <!-- 角色 -->
        <el-table-column prop="members" label="是否为会员"> </el-table-column>
        <el-table-column width="270px" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="showeditdialog(scope.$index, scope.row)"
              icon="el-icon-edit"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="deleteuser(scope.$index, scope.row)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 4, 5, 6]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 手机号验证
    let checkMobile = (rule, value, cb) => {
      const regmobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (regmobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      input: "",
      currentPage: 1, // 当前页码
      total: 1, // 总条数
      pageSize: 6, // 每页的数据条数
      userlist: [], //存放客户信息的列表
      dialogVisible: false, // 添加的模态框
      editdialogVisible: false, // 修改的模态框
      edituserinfo: [], // 修改模态框的表单数组
      myIndex: 0,
      // 添加模态框的值
      addform: {
        clientname: "",
        sex: "",
        birth: "",
        mobile: "",
        members: "",
      },
      // 表单验证
      addroles: {
        clientname: [
          { required: true, message: "请输入客户名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        sex: [{ required: true, message: "请选择", trigger: "change" }],
        birth: [
          {
            // 在进行日期验证时，要把删掉type：date，因为在进行数据双向绑定s
            required: true,
            message: "请选择出生日期",
            trigger: "change",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        members: [{ required: true, message: "请选择", trigger: "change" }],
      },
      // 实现日期快捷选择
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },
  created() {
    // 初始化
    let obj = sessionStorage.getItem("userlist");
    if (obj != null) {
      // 从缓存中获取，把json字符串先转换成对象数组
      this.userlist = JSON.parse(obj);
    }
    this.init();
  },
  methods: {
    // 获取客户信息
    async init() {
      let result = await this.myAxios.get("/getclient");
      if (result.status === 200) {
        this.userlist = result.data.RECORDS;
        // 把数据长度赋给total
        this.total = result.data.RECORDS.length;
      } else {
        alert(result.StatusText);
      }
    },
    // 删除用户信息
    deleteuser(index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          // console.log(res);
          if (res === "confirm") {
            this.userlist.splice(index, 1);
            this.total -= 1;
            sessionStorage.setItem("userlist", JSON.stringify(this.userlist));
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 添加客户信息
    adduser(formName) {
      // 点击添加后判断表单是否为空
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.userlist.push(this.addform);
          this.total = this.userlist.length;
          this.dialogVisible = false;
          this.$message.success("添加客户成功");
        }
        // console.log(this.userlist);
        return this.userlist;
      });
      this.addform = new Object();
      // 更新缓存
      sessionStorage.setItem("userlist", JSON.stringify(this.userlist));
    },
    // 通过模态框展示哪一行的信息
    showeditdialog(index) {
      this.editdialogVisible = true;
      this.edituserinfo = this.userlist[index];
    },
    // 修改后将值重新赋给客户信息列表
    edituser(index) {
      this.$refs.edituserinforef.validate((valid) => {
        if (valid) {
          console.log(index);
          this.userlist[index] = this.edituserinfo;
          this.editdialogVisible = false;
        }
      });
    },
    //监听 pagesize 改变的事件
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //监听页码值 改变的事件
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
  },
  // mounted: {
  //   tables() {},
  // },
  computed: {
    tables() {
      // 输入框中输入的值
      const input = this.input;
      if (input) {
        return this.userlist.filter((data) => {
          // some()用于检测数组中的元素是否满足指定条件
          return Object.keys(data).some(() => {
            return String(data["clientname"]).toLowerCase().indexOf(input) > -1;
          });
        });
      }

      return this.userlist.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
  },
};
</script>

<style>
.box-card {
  margin-top: 20px;
}
</style>